package com.fang.common.exception;

/**
 * @author Fang Ruichuan
 * @date 2022-08-28 12:12
 */

import com.fang.common.wrapper.ResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = RuntimeException.class)
    public ResponseWrapper handle(RuntimeException e) {
        log.error("运行时异常: ---------------- {}", e.getMessage());
        return ResponseWrapper.fail(e.getMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public ResponseWrapper handle(IllegalArgumentException e) {
        log.error("Assert异常: ---------------- {}", e.getMessage());
        return ResponseWrapper.fail(e.getMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseWrapper handle(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        ObjectError objectError = result.getAllErrors().stream().findFirst().get();
        log.error("接口入参校验异常: ---------------- {}", objectError.getDefaultMessage());
        return ResponseWrapper.fail(objectError.getDefaultMessage());
    }
}
